package com.ys.controller.api.business;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.business.ThrCanvassApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.ThrCanvassApplyItemService;
import com.ys.service.business.ThrCanvassApplyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/thrCanvassApply")
public class ApiInterThrCanvassApplyController {
    //private static Long MENU_ID_DETAIL = 10214L;
    private static final Logger logger = LoggerFactory.getLogger(ApiInterThrCanvassApplyController.class);
    @Autowired
    private CommonApiService<ThrCanvassApply> commonApiService;
    @Autowired
    private ThrCanvassApplyService thrCanvassApplyService;

    @Autowired
    private ThrCanvassApplyItemService thrCanvassApplyItemService;

    @Autowired
    private YspTaskService yspTaskService;
    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public ThrCanvassApply setSeachSql(ThrCanvassApply cond){


        cond
                .addField("'Amazon' AS platform")
                .addField("E.Name AS institutionName")
                .addField("B.Pbid AS bid")
                .addField("B.Vgsmc AS vgsmc")
                .addField("B.Vgsjc AS vgsjc")
                .addField("B.Vgsbm AS vgsbm")
                .addField("B.PlatformManager AS platformManager")
                .addField("B.InvestType AS investType")
                .addField("B.CostStandard AS costStandard")
                .addField("B.Corporation AS corporation")
                .addField("U.UserName AS createUser")
                .addField("U.DeptName AS createPosition")
                .addField("E.Pid AS vgsBmp")
                .addField("P.Name AS vgsJcp")

                //.addField("G.Name AS region")
                //.addField("F.CountryName AS country")

                .addLeftJoin("TS_UserChange AA on AA.Id=A.Operateperson")
                .addLeftJoin("TS_UserInfo U on U.UserId = AA.UserId")
                .addLeftJoin("TS_UserInfo C on C.UserId = U.UserLeader")
                .addLeftJoin("YS_Role PR ON PR.Id = C.RoleId AND 1=1")
                .addLeftJoin("TS_OrganizationInfo PO ON PO.Orgid = C.DeptId AND 1=1")
                .addField("AA.UserId AS userId")
                .addField("AA.UserName AS operatepersonName")
                .addField("AA.RoleName AS roleName")
                .addField("AA.DeptName AS deptName")
                .addField("C.UserName AS superiorpersonnel")
                .addField("PR.Name AS superiorposition")
                .addField("PO.DeptName AS superiordepartment")
                .addField("'Amazon' AS registrationRequire")
                .addField("CASE WHEN GG.EffectStock IS NULL or GG.EffectStock=0 THEN '未完成' ELSE '已完成' END _ys_filingStatus ")
                .addField("CASE WHEN A.EffectStock IS NULL or A.EffectStock=0 THEN '未流转' ELSE '流程结束' END effectStock ")
//                    .addField("A.HeadUserId + '/' + U.UserName AS headUserName")
                .addLeftJoin("THR_CanvassApplyItem B ON A.Bid = B.Pbid ")
                .addLeftJoin("TS_OperateOrg E ON E.Id = B.InstitutionId and 1=1")
                .addLeftJoin("TS_OperateOrg P on P.Id = E.Pid")

                .addLeftJoin("TB_Site S ON S.Id = B.SiteId and 1=1")
                .addLeftJoin("TP_AmazonRegion AR ON AR.Code = S.RegionCode")
                .addField("AR.Name region")

                .addLeftJoin("TB_Country CT ON CT.Id = S.CountryId")
                //.addField("C.Code countryCode")
                .addField("CT.Name country")

                .addLeftJoin("THR_OperateCompanyBeian GG ON GG.Code = B.Vgsbm and 1=1");

        //排序
        cond.setOrderby("A.Bid DESC");
        cond = commonApiService.dataAuth(MenuId.THR_CanvassApply, cond);
        return  cond;
    }

    @RequiresPermissions("thrCanvassApply:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute ThrCanvassApply cond,String conditions
    ){
        cond = setSeachSql(cond);
        //查询条件
        String filingStatus = ConditionUtil.getConditionValue(conditions, "_ys_filingStatus");
        if (filingStatus != null){
            if(filingStatus.equals("未完成")){
                cond.where(" GG.EffectStock IS NULL or GG.EffectStock=0 ");
            }else{
                cond.where(" GG.EffectStock=1 ");
            }
        }
        return commonApiService.searchLay(cond);
    }

    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute ThrCanvassApply cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.THR_CanvassApply)
                    .where("A.Code != 'ope'")
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<ThrCanvassApply> util = new ExportExcelUtils<>(new ThrCanvassApply());
            String toFilePath = util.exportExcel(listData, listField, "员工档案");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params, String subData) {
        try {
            logger.info("申请新增传参：" + params);
            return thrCanvassApplyService.add(params,MenuId.THR_CanvassApply);
        } catch (Exception e) {
            logger.error("新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 编辑
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return thrCanvassApplyService.update(params,MenuId.THR_CanvassApply);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 流转通过
     */
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return thrCanvassApplyService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("流转出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        ThrCanvassApply entity = new ThrCanvassApply().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        ThrCanvassApply entity = new ThrCanvassApply().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return thrCanvassApplyService.delete(id);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 删除列表信息
     */
    @RequestMapping("/toDelItem")
    @ResponseBody
    public R toDelItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                //删除
                thrCanvassApplyItemService.del(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }

    }
}

